#include "thread.h"
#include <stdio.h>
#include <assert.h>

static void * fibonacci(void * arg){
  long int n=*(long int*)arg;	
  void * retval=arg;
  if(n==1||n==2){
    *(long int*)retval=1;
    thread_exit(retval);
  }
  else if(n==0){
    *(long int*)retval=0;
    thread_exit(retval);
  }
  else{
  thread_t thread[2];
  void * fibo[2];
  fibo[0]=NULL;
  fibo[1]=NULL;
  long int indice[2];
  indice[0]=n-1;
  indice[1]=n-2;
  int err;
  err=thread_create(&thread[0], fibonacci,(void *)&indice[0]);
  assert(!err);
  err=thread_create(&thread[1], fibonacci,(void *)&indice[1]);
  assert(!err);
  err=thread_join(thread[1],&fibo[1]);
  assert(!err);
  err=thread_join(thread[0],&fibo[0]);
  assert(!err);
  *(long int*)retval=*(long int*)fibo[0]+*(long int*)fibo[1];
  thread_exit(retval);
  }
}

int main(int argc, char *argv[])
{
if(argc==2){
  long int i= atol(argv[1]);
  thread_t thread;
  void * retval;
  thread_create(&thread,fibonacci,(void *)&i);
  thread_join(thread, &retval);
  printf("Fibonacci(%li)=%li\n",i,*(long int*)retval);
  return EXIT_SUCCESS;
  }
  else{
  printf("Argument invalide\n");
  return EXIT_FAILURE;
  }
}


